<html>
<head>
<script language='JavaScript' src='/scripts/scripts.js'>");
</script>
<link href="/styles/clmenu.css" type="text/css" rel="stylesheet">
<link href="/styles/xajaxGrid.css" type="text/css" rel="stylesheet">
<?php
$noajax = 1;
$projectid=3;
include('./xajax_config.php');
include_once('../lib_verify.php');
include_once('./lib_cova_summary.php');
$xajax->printJavascript("$liburl/xajax");
error_reporting(E_ERROR);
$runid = 0;
$scenarioid = 37;
print("</head><body>");
if (isset($_GET['elementid'])) {
   $elementid = $_GET['elementid'];
}
if (isset($_GET['metrics'])) {
   $metrics = $_GET['metrics'];
} else {
   $metrics = array('avg');
}
if (isset($_GET['hsivar'])) {
   $hsivar = $_GET['hsivar'];
} else {
   $hsivar = array();
}
if (isset($_GET['runs'])) {
   $runs = $_GET['runs'];
} else {
   $runs = array();
}
if (isset($_GET['startdate'])) {
   $startdate = $_GET['startdate'];
} else {
   $startdate = '1984-10-01';
}
if (isset($_GET['enddate'])) {
   $enddate = $_GET['enddate'];
} else {
   $enddate = '2005-09-30';
}
if (isset($_GET['Qmin'])) {
   $Qmin = $_GET['Qmin'];
} else {
   $Qmin = 20;
}
if (isset($_GET['Qmax'])) {
   $Qmax = $_GET['Qmax'];
} else {
   $Qmax = 700;
}

$allruns = array();
// START - AUTO RUN SETUP
// define runs based on Data base query
$runlist = getModelRunList($listobject, $elementid, -1);
foreach ($runlist as $thisrun) {
   $allruns[] = array('option'=>$thisrun['runid'], 'label'=>"Run " . $thisrun['runid']);
}
asort($allruns);
// DONE - AUTO RUN SETUP

/*
// START - MANUAL RUN SETUP
// define runs based on manual setup
// run ids / names
$allruns[] = array('option'=>'0', 'label'=>'Baseline');
$allruns[] = array('option'=>'1', 'label'=>'Historic');
//$allruns[] = array('option'=>'6', 'label'=>'3-Tier 20-30-40');
$allruns[] = array('option'=>'5', 'label'=>'2-Tier 20-30 (W)');
$allruns[] = array('option'=>'7', 'label'=>'2-Tier 20-30 (B)');
$allruns[] = array('option'=>'8', 'label'=>'WQ Target (rec)');
$allruns[] = array('option'=>'9', 'label'=>'WQ Target');
$allruns[] = array('option'=>'10', 'label'=>'WQ Target (May-June rec)');
// DONE - MANUAL RUN SETUP

*/


$allmetrics[] = array('option'=>'r_quantile,0.01', 'label'=>'1st %ile');
$allmetrics[] = array('option'=>'r_quantile,0.05', 'label'=>'5th %ile');
$allmetrics[] = array('option'=>'r_quantile,0.1', 'label'=>'10th %ile');
$allmetrics[] = array('option'=>'r_quantile,0.25', 'label'=>'25th %ile');
$allmetrics[] = array('option'=>'r_quantile,0.75', 'label'=>'75th %ile');
$allmetrics[] = array('option'=>'r_quantile,0.9', 'label'=>'90th %ile');
$allmetrics[] = array('option'=>'median', 'label'=>'Median');
$allmetrics[] = array('option'=>'avg', 'label'=>'Mean');
$allmetrics[] = array('option'=>'duration', 'label'=>'Duration Plot');
$allmetrics[] = array('option'=>'habitat_duration', 'label'=>'Habitat Duration Plot');
$allmetrics[] = array('option'=>'timeseries', 'label'=>'Timer Series');

// instantiate the object of interest
//print("Unserializing $elementid <br>");
$unres = unSerializeSingleModelObject($elementid);
$thisobject = $unres['object'];
 // get the possible variables that hold the WUA info
$subcomps = $thisobject->getPublicProcs();
//print("Sub-Comps: " . print_r($subcomps,1) . "<br>");
// set up a where query for restricting conditions - UNDER DEVELOPMENT
//$qwiz = showAnalysisQueryWizard (array('elementid'=>$elementid), $session_table, $form_name, $mode = 'xajax')
//$whereform = $thisobject->showWhereFields('hsiform', 0);


$varoptions = array();
foreach ($subcomps as $thiscomp) {
   $varoptions[] = array('hsivar' => $thiscomp);
   // set the first var as the default if none is currently selected
   if ( ($hsivar == '') or ( ($hsivar <> '') and !in_array($hsivar, $subcomps)) ) {
      $hsivar = $thiscomp;
   }
}
$options_only = 0;
$varselect = showActiveList($varoptions, 'hsivar', 'hsivar', 'hsivar', 'hsivar', '' ,$hsivar, '', 'hsivar', 0, 1, 0, '', 0, $options_only);


// get the values of variable to plot
// BEGIN - automatically define options
$varcolnames = $thisobject->processors[$hsivar]->colnames;
//print("Possible column headers" . print_r($varcolnames,1) . "<br>");
foreach ($varcolnames as $thiscolname) {
   $opt = $hsivar . "_" . $thiscolname;
   $allspecies[] = array('option'=>$opt, 'label'=>$thiscolname);
}
if (isset($_GET['species'])) {
   $species = $_GET['species'];
} else {
   $species = $allspecies[0]['option'];
}
// END - automatically define options
/*
// BEGIN - manually define options
$allspecies[] = array('option'=>'shad_spawning', 'label'=>'Shad, Spawning');
$allspecies[] = array('option'=>'shad_juvenile', 'label'=>'Shad, Juvenile');
$allspecies[] = array('option'=>'hogsucker_adult', 'label'=>'Northern Hogsucker, Adult');
$allspecies[] = array('option'=>'hogsucker_spawn', 'label'=>'Northern Hogsucker, Spawning');
$allspecies[] = array('option'=>'lampsilis_radiata', 'label'=>'Lampsilis Radiata');
$allspecies[] = array('option'=>'elliptio_complanata', 'label'=>'Elliptio Complanata');
// END - manually define options
*/

print("<form action='$scriptname' method=GET id='hsiform' name='hsiform'>");
$run_select = showMultiCheckBox('runs', $allruns, $runs, ' | ', '', 1, 0);
$stat_select = showMultiCheckBox('metrics', $allmetrics, $metrics, ' | ', '', 1, 0);
$species_select = showMultiCheckBox('species', $allspecies, $species, ' | ', '', 1, 0);
print("<b>Select Variable:</b> " . $varselect . "<br>");
print("Start Date: <input type='date' name='startdate' value='$startdate'><br>");
print("End Date: <input type='date' name='enddate' value='$enddate'><br>");
print("<b>Select Species:</b> " . $species_select . "<br>");
print("<b>Select Habitat Suitability Statistics:</b> " . $stat_select . "<br>");
print("<b>Select Scenarios:</b> " . $run_select . "<br>");
print("<b>Select Minimum Inflow:</b> " . showWidthTextField('Qmin',$Qmin, 8, '', 1) . "<br>");
print("<b>Select Maximum Inflow:</b> " . showWidthTextField('Qmax',$Qmax, 8, '', 1) . "<br>");
showHiddenField('elementid', $elementid, 0);
showSubmitButton('submit',"Show Graphs", '', 0, 0);
print("<hr>");

// should replace this definition with a query to look for children that are HSI's
$hsi_element = $elementid;

$elinfo = getElementInfo($listobject, $elementid);
if (isset($elinfo['scenarioid'])) {
   $scenarioid = $elinfo['scenarioid'];
}
//$debug = 1;
foreach ($runs as $thisrunid) {
   print("Retrieving element $hsi_element, run $thisrunid <br>");
   $rundata = retrieveRunSummary($listobject, $hsi_element, $thisrunid);
   if ($debug) {
      print(print_r($rundata,1) . "<hr>");
   }
   if (strlen(trim($rundata['run_summary'])) == 0) {
      $elname = getElementName($listobject, $elementid);
      $order = $rundata['order'];
      $status = $rundata['run_status'];
      print("No run info stored for $elname ($elementid) <br>\n");
      print("Run Status: $status <br>\n");
      if ($debug) {
         $rundata['message'] .= "Query: " . $rundata['query'] . "<br>\n";
      }
   } else {
      $rundata['message'] = $rundata['run_summary'];
   }
}
$listobject->querystring = "  select runid from scen_model_run_elements where elementid = $hsi_element and runid in ( " . join(',', $runs) . ") ";
$listobject->performQuery();
foreach ($listobject->queryrecords as $rr) {
   $runids[] = $rr['runid'];
}
//sort($runids);

// BEGIN - Create Fllow Comparison Graphs
// print out graphical comparisons of flows
// show check boxes for runs to compare (to do later)
//$debug = 1;
//$runids = array(0,2);

$restrictions = array();
//$restrictions['Qin'][] = array('op'=>'>', 'val'=> $Qmin);
//$restrictions['Qin'][] = array('op'=>'<', 'val'=> $Qmax);
$restrictions['Qout'][] = array('op'=>'>=', 'val'=> $Qmin);
$restrictions['Qout'][] = array('op'=>'<=', 'val'=> $Qmax);

foreach ($species as $this_species) {
   // get the runids that actualy exist so as not to create bad graph objects
   //$runids = array(0,1);
   //print("$listobject->querystring ; <br>" . print_r($runids,1) . "<br>");
   $doquery = 1; // set to 0 to just assemble but not execute the query
   $variables = $this_species;
   //print("Getting element: $hsi_element - runs: " . join(',',$runids) . ", vars: $variables from $startdate to $enddate, $doquery, $debug <br>");
   $result = compareRunData($hsi_element, join(',',$runids), $variables, $startdate, $enddate, $doquery, $debug, $restrictions, 'inner');
   // show 
   if ($debug) {
      print(print_r($result,1) . "<br>");
      print(print_r($result['query'],1) . "<br>");
   }
   
   $legends = array();
   foreach ($allruns as $thisone) {
      $legends[$this_species . "_" . $thisone['option']] = $thisone['label'];
   }
   $result['legends'] = $legends;
   $result['ylabel'] = 'Weighted Usable Area';
   $result['xlabel'] = 'Month';
   $r_restrict = array();
   foreach ($result['valid_cols'] as $spec_col) {
      $r_restrict[$spec_col][] = array('op'=>'is not', 'val'=> 'NULL');
   }
   foreach ($metrics as $thismetric) { 
      $title = ucwords($thismetric) . ' ' . ucwords ($this_species);
      if ($debug) {
         print("Restrict: " . print_r($r_restrict,1) . "<br>");
      }
      switch ($thismetric) {
         
         case 'timeseries':
            $vars = "$variables,Qout";
             foreach ($allruns as $thisone) {
               $legends["Qout_" . $thisone['option']] = $thisone['label'];
            }
            $Qresult['legends'] = $legends;
            $Qresult['ylabel'] = 'Weighted Usable Area';
            $Qresult['xlabel'] = 'Month';
            $Qresult = compareRunData($hsi_element, join(',',$runids), $vars, $startdate, $enddate, $doquery, $debug, $restrictions, 'inner');
            //print("Valid Columns:" . print_r($Qresult['valid_cols'],1) . "<br>");
            $graphout = cova_graphHabitatTimeSeries($Qresult, $debug, $r_restrict, 2, 800, 600, $this_species . $thismetric, $title);
            if ($debug) {
               print($graphout['query'] . "<br>");
               print($graphout['debug'] . "<br>");
            }
         break;
         
         case 'duration':
            $vars = "Qout";
            $Qresult = compareRunData($hsi_element, join(',',$runids), $vars, $startdate, $enddate, $doquery, $debug, array(), 'inner');
             foreach ($allruns as $thisone) {
               $legends["Qout_" . $thisone['option']] = $thisone['label'];
            }
            $Qresult['legends'] = $legends;
            //print("Valid Columns:" . print_r($Qresult['valid_cols'],1) . "<br>");
            $graphout = cova_graphDuration($Qresult, $debug, $r_restrict, 2, 800, 600, "flow_duration",  "Flow Duration");
            // create a joined query, get the column names
            // add a duration plot subcomp to a duration object for each requested run
            // generate the plot
            if ($debug) {
               print($graphout['query'] . "<br>");
               print($graphout['debug'] . "<br>");
            }
         break;
         
         case 'habitat_duration':
            $graphout = cova_graphDuration($result, $debug, $r_restrict, 2, 800, 600, "habitat_duration", "$this_species Habitat Duration");
            // create a joined query, get the column names
            // add a duration plot subcomp to a duration object for each requested run
            // generate the plot
            if ($debug) {
               print($graphout['query'] . "<br>");
               print($graphout['debug'] . "<br>");
            }
         break;
         
         default:
            $graphout = cova_graphHabitatComparison2($result, $thismetric, $debug, $r_restrict, 2, 800, 600, $this_species . $thismetric, $title);
            if ($debug) {
               print($graphout['query'] . "<br>");
               print($graphout['debug'] . "<br>");
            }
         break;
      }
      
      $graphurl = $graphout['img_url'];
//      if ($debug) {
         print($graphout['query'] . "<br>");
//      }
      print("<img src='$graphurl'>");
      print($graphout['data_table'] . "<br>");
   }


} // end species loop


?>
</body>
</html>
